﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjCreator : MonoBehaviour
{
    public Rigidbody2D Obj;
    public float leftPos;
    public float rightPos;
    public float topPos;
    public float bottomPos;
    public float minSpawnTime;
    public float maxSpawnTime;
    public float minSpeed;
    public float maxSpeed;

    // Start is called before the first frame update
    void Start()
    {
        Random.InitState(System.DateTime.Today.Millisecond);
        StartCoroutine(Spawn());
    }

    IEnumerator Spawn()
    {
        float betweenTime = Random.Range(minSpawnTime, maxSpawnTime);
        yield return new WaitForSeconds(betweenTime);

        bool faceR = Random.Range(0, 2) == 1;
        float x = faceR ? leftPos : rightPos;
        float y = Random.Range(bottomPos, topPos);

        Rigidbody2D objInstance = Instantiate(Obj, new Vector3(x, y, transform.position.z), Quaternion.identity);
        objInstance.velocity = new Vector2(-Random.Range(minSpeed, maxSpeed), 0);
        if (faceR)
        {
            Vector3 scale = objInstance.transform.localScale;
            scale.x *= -1;
            objInstance.transform.localScale = scale;
            objInstance.velocity *= -1;
        }
        StartCoroutine(Spawn());

        while (objInstance != null)
        {
            if (faceR)
            {
                if (objInstance.transform.position.x > rightPos + 0.5f)
                    Destroy(objInstance.gameObject);
            }
            else
            {
                if (objInstance.transform.position.x < leftPos - 0.5f)
                    Destroy(objInstance.gameObject);
            }
            yield return null;
        }
    }
}
